<template>
  <XcDrawer ref="drawer" :title="$t('page.base.task')" :width="640" @onDrawerSave="onSave">
    <Form ref="taskform" :model="task" :label-width="0" :rules="rules">
      <FormItem prop="task">
        <Input v-model="task.task" maxlength="32" :placeholder="$t('page.base.task')" :show-word-limit="adding" :disabled="!adding"></Input>
      </FormItem>
      <FormItem prop="namespace">
        <CompNschoose :current="task.namespace" @onChosen="chooseNs" :showmode="!adding" />
      </FormItem>
      <FormItem prop="remark">
        <Input v-model="task.remark" type="textarea" show-word-limit maxlength="64" :autosize="{minRows:3}" :placeholder="$t('form.remark')"></Input>
      </FormItem>
    </Form>
  </XcDrawer>
</template>
<script>
  import XcDrawer from '@/components/xcdrawer'
  import CompNschoose from '@/components/nschoose'
  export default {
    name: 'comp-task-edit',
    components: { XcDrawer, CompNschoose },
    data() {
      return {
        adding: false,
        task: {
          task: '',
          namespace: '',
          remark: ''
        },
        rules: {
          task: [{ required: true, max: 32, pattern: /^[a-zA-Z][a-zA-Z0-9_]{1,32}/, message: this.$t('page.base.taskform.namerule'), trigger: 'blur' }],
          remark: [{ required: true, max: 64, message: this.$t('form.inputrule', [this.$t('form.remark')]), trigger: 'blur' }],
        },
      }
    },
    methods: {
      show(task) {
        this.$refs.taskform.resetFields()
        //
        task = task || {}
        this.task.task = task.task || ''
        this.task.namespace = task.namespace || ''
        this.task.remark = task.remark || ''
        this.adding = this.task.task === ''
        //
        this.$refs.drawer.show()
      },
      chooseNs(ns) {
        this.task.namespace = ns
      },
      onSave() {
        this.$refs.taskform.validate((valid) => {
          if (valid) {
            let name = this.task.task.toLowerCase()
            let allNs = this.$t('page.base.nsall')
            let namespace = this.task.namespace
            if (namespace === allNs) namespace = ''
            this.$md.dispatch('task_edit', {
              data: {
                task: name,
                namespace: namespace,
                remark: this.task.remark,
              }
            }).then(data => {
              if (data.retCode === 1) {
                this.$refs.drawer.close(true)
                this.$emit('onRefresh')
              }
            })
          }
        })
      }
    }
  }
</script>
